"use client"

import { AuthGuard } from "@/components/auth-guard"
import { DashboardLayout } from "@/components/dashboard-layout"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Plus, Play, Pause, MoreVertical, Copy, Trash2, Bot } from "lucide-react"
import Link from "next/link"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { useEffect, useState } from "react"

interface Agent {
  id: string
  name: string
  components: any[]
  edges: any[]
  status: string
  lastRun: string
  createdAt: string
  updatedAt: string
}

export default function AgentsPage() {
  const [agents, setAgents] = useState<Agent[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    loadAgents()
  }, [])

  const loadAgents = async () => {
    try {
      const response = await fetch("/api/agents")
      const result = await response.json()
      if (result.success) {
        setAgents(result.data)
      }
    } catch (error) {
      console.error("Failed to load agents:", error)
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async (agentId: string) => {
    if (!confirm("确定要删除这个 Agent 吗？")) {
      return
    }

    try {
      const response = await fetch(`/api/agents?id=${agentId}`, {
        method: "DELETE",
      })
      const result = await response.json()
      if (result.success) {
        // 重新加载列表
        loadAgents()
      } else {
        alert("删除失败: " + result.error)
      }
    } catch (error) {
      console.error("Failed to delete agent:", error)
      alert("删除失败")
    }
  }

  if (loading) {
    return (
      <AuthGuard>
        <DashboardLayout>
          <div className="flex items-center justify-center h-64">
            <p className="text-muted-foreground">加载中...</p>
          </div>
        </DashboardLayout>
      </AuthGuard>
    )
  }
  return (
    <AuthGuard>
      <DashboardLayout>
        <div className="space-y-6">
          {/* Header */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold tracking-tight">Agent 管理</h1>
              <p className="text-muted-foreground mt-2">创建和管理您的 AI Agent</p>
            </div>
            <Link href="/dashboard/agents/new">
              <Button>
                <Plus className="mr-2 h-4 w-4" />
                创建 Agent
              </Button>
            </Link>
          </div>

          {/* Agents Grid */}
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            {agents.map((agent) => (
              <Card key={agent.id} className="hover:shadow-md transition-shadow">
                <CardHeader>
                  <div className="flex items-start justify-between">
                    <div className="flex items-start gap-3 flex-1">
                      <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
                        <Bot className="h-5 w-5 text-primary" />
                      </div>
                      <div className="space-y-1 flex-1 min-w-0">
                        <CardTitle className="text-lg truncate">{agent.name}</CardTitle>
                        <CardDescription className="line-clamp-2">
                          {agent.components?.length || 0} 个组件 · {agent.edges?.length || 0} 个连接
                        </CardDescription>
                      </div>
                    </div>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon" className="h-8 w-8 flex-shrink-0">
                          <MoreVertical className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem>
                          <Copy className="mr-2 h-4 w-4" />
                          复制
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          className="text-destructive"
                          onClick={() => handleDelete(agent.id)}
                        >
                          <Trash2 className="mr-2 h-4 w-4" />
                          删除
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center gap-2">
                    <Badge variant="outline">LangGraph</Badge>
                    <Badge variant={agent.status === "active" ? "default" : "secondary"}>
                      {agent.status === "active" ? "运行中" : agent.status === "draft" ? "草稿" : "已暂停"}
                    </Badge>
                  </div>
                  <div className="space-y-2">
                    <p className="text-xs text-muted-foreground">组件类型</p>
                    <div className="flex flex-wrap gap-1">
                      {agent.components?.slice(0, 5).map((component, index) => (
                        <Badge key={index} variant="secondary" className="text-xs">
                          {component.label || component.type}
                        </Badge>
                      ))}
                      {agent.components && agent.components.length > 5 && (
                        <Badge variant="secondary" className="text-xs">
                          +{agent.components.length - 5}
                        </Badge>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center justify-between text-sm text-muted-foreground">
                    <span>上次运行: {agent.lastRun}</span>
                    <span>更新: {agent.updatedAt}</span>
                  </div>
                  <div className="flex gap-2">
                    <Link href={`/dashboard/agents/${agent.id}`} className="flex-1">
                      <Button variant="outline" className="w-full bg-transparent">
                        编辑
                      </Button>
                    </Link>
                    <Button variant="outline" size="icon">
                      {agent.status === "active" ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      </DashboardLayout>
    </AuthGuard>
  )
}
